var express = require('express');
var router = express.Router();
var TestModel = require('../modals/test');

/* GET home page. */
router.get('/', function(req, res, next) {
	TestModel.findOne({
		id: 0
	}, function(err, test) {
		if (err) {
			console.log(err)
		};
		var num = 0;
		if (test) {
			num = test.num
		} else {
			TestModel.create({
				id: 0,
				num: 0
			}, function(err) {
				if (err) {
					console.log(err)
				} else {
					console.log('save ok')
				}
			})
		};
		res.render('index.html', {
			test: num
		});
	})
});

router.post('/', function(req, res, next) {
	var num = parseInt(req.body.num);
	TestModel.findOne({id:0}, function(err, test) {
		if (err) { res.status(500);res.send({err:err}) }
		var testNum = parseInt(test.num);
		test.num = testNum + num;
		test.save(function(err,resp) {
			if (err) {console.log(err)}
			res.send({data:resp})
		})
	})
});

module.exports = router;